<?php

namespace app\common\model;

use app\api\model\DeveloperException;
use app\api\model\ServerException;
use app\api\model\TokenException;
use app\api\model\UserException;
use think\facade\Cache;
use think\facade\Db;

class OrderVerify extends Base
{
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    /**
     * $order_id
     * @param $order_id
     * @param $user
     * @return array
     * @throws UserException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static public function verifyPage($order_id,$user=false){
        $order = Db::name('order')
            ->where('id','=',$order_id)
            ->find();
        if(!$order){
            throw new UserException('无此订单');
        }

        if($order['type']!=1){
            throw new UserException(get_base_type(3,$order['type']).'订单无法核销');
        }

        if($order['status']==0){
            throw new UserException('订单还未支付');
        }

        if($order['status']==-1){
            throw new UserException('订单已取消');
        }

        $merch = Merch::getInfo($order['merch_id']);

        //自己可以看自己的订单  若不是自己的订单看下是不是核销员
        if($user && $order['uid']!=$user['id']){
            //查信息的人是否是 订单对应商家下的核销员
            $worker = Db::name('merch_worker')
                ->where('uid','=',$user['id'])
                ->field('id,merch_id,status,name,avatar')
                ->find();
            if(!$worker){
                throw new UserException('你不是核销员，无法核销');
            }
            if($worker['merch_id']!=$order['merch_id']){
                throw new UserException("你不是商家【{$merch['title']}】的核销员，无法核销此订单");
            }
            if($worker['status']!=1){
                throw new UserException('你的核销员身份已被禁用，无法核销');
            }
        }

        //商品
        $order_goods = Db::name('order_goods')
            ->where('order_id','=',$order_id)
            ->field('goods_id,type,activity_type,title,thumb,price,spec_item_title,num,leave_num')
            ->select()
            ->toArray();

        $coin_title = config('self.user_coin_title');

        //剩余
        $leave_num = 0;

        foreach ($order_goods as &$item){
            $item['spec_item_title'] = str_replace('+','、',$item['spec_item_title']);
            $item['thumb'] = manageImg($item['thumb']);
            if($item['activity_type']==2){
                $item['price'] = ($item['price']+0).$coin_title;
            }else{
                $item['price'] = '￥'.($item['price']+0);
            }

            $leave_num += $item['leave_num'];
            unset($item['leave_num']);
        }
        unset($item);

        //剩余份数
        if($order['status']>=3){
            $leave_num = 0;
        }

        //价格显示
        $price_arr = [];

        if($order['activity_type']!=2){
            if($order['dispatch_price']>0){
                $price_arr[] = [
                    'show_type'=>'1',
                    'title'=>'配送费',
                    'value'=>'￥'.$order['dispatch_price']
                ];
            }

            if($order['coin_deduct']>0){
                $price_arr[] = [
                    'show_type'=>'1',
                    'title'=>$coin_title.'抵扣',
                    'value'=>'-￥'.$order['coin_deduct']
                ];
            }

            $price_arr[] = [
                'show_type'=>'2',
                'title'=>'订单金额',
                'value'=>'￥'.$order['order_price']
            ];
        }else{
            $price_arr[] = [
                'show_type'=>'2',
                'title'=>'订单金额',
                'value'=>$order['order_price'].$coin_title
            ];
        }

        //核销记录
        $verify_log = self::where('order_id',$order_id)
            ->field('verify_type,num,create_time')
            ->order('id DESC')
            ->select()
            ->each(function ($item){
                if($item['verify_type']==1){
                    $item['title'] = get_goods_verify_type(3,1);
                    $item['value'] = $item['create_time'];
                }else{
                    $item['title'] = "核销{$item['num']}次";
                    $item['value'] = $item['create_time'];
                }
                unset($item['verify_type']);
                unset($item['num']);
                unset($item['create_time']);
                return $item;
            })
            ->toArray();
        array_unshift($verify_log,['title'=>'订单单号','value'=>$order['order_sn']]);

        return [
            'verify_type'=>$order['verify_type'],
            'merch'=>[
                'id'=>$order['merch_id'],
                'type'=>$merch['type'],
                'title'=>$merch['title'],
            ],
            'order_goods'=>$order_goods,
            'price_arr'=>$price_arr,
            'all_num'=>$order['goods_num'],
            'use_num'=>$order['goods_num']-$leave_num,
            'leave_num'=>$leave_num,
            'info'=>$verify_log
        ];
    }

    /**
     * 核销提交
     * @param $user
     * @param $order_id
     * @param $num
     * @throws ServerException
     * @throws UserException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static public function verifySub($user=false,$order_id,$verify_code,$num,$type=1,$admin_id=0,$admin_name=''){
        $order = Db::name('order')
            ->where('id','=',$order_id)
            ->find();
        if(!$order){
            throw new UserException('无此订单或无权操作');
        }

        if($order['type']!=1){
            throw new UserException(get_base_type(3,$order['type']).'订单无法核销');
        }

        if($order['status']==0){
            throw new UserException('订单还未支付，无法核销');
        }

        if($order['status']==-1){
            throw new UserException('订单已取消，无法核销');
        }

        if($order['status']>=3){
            throw new UserException('订单已完成，无法核销');
        }

        if($order['status']<=-2){
            throw new UserException('订单已申请售后，无法核销');
        }

        if($verify_code!=$order['verify_code']){
            throw new UserException('核销码错误，请检查是否输入了空格等');
        }

        if($order['is_expire']>0&&$order['expire_time']<time()){
            throw new UserException('订单已超过有效期'.date('Y-m-d H:i',$order['expire_time']));
        }

        $merch = Merch::getInfo($order['merch_id']);

        if($type==1){
            //店员核销判断店员
            //查信息的人是否是 订单对应商家下的店员
            $worker = Db::name('merch_worker')
                ->where('uid','=',$user['id'])
                ->field('id,merch_id,status,name')
                ->find();
            if(!$worker){
                throw new UserException('你不是核销员，无法核销');
            }
            if($worker['merch_id']!=$order['merch_id']){
                throw new UserException("你不是商家【{$merch['title']}】的核销员，无法核销");
            }
            if($worker['status']!=1){
                throw new UserException('你的核销员员身份已被禁用，无法核销');
            }

            $admin_id = $worker['id'];
            $admin_name = $worker['name'];
        }elseif ($type==2){
            //商家后台核销
        }elseif($type==3){
            //总平台操作
        }elseif($type==4){
            //县代
        }elseif($type==5){
            //城市合伙人
        }else{
            throw new UserException('无此方式');
        }

        $finish = false;//订单完成默认否
        if($order['verify_type']==1){
            //核销类型及次数
            $verify_type = 1;
            $num = 1;

            //整单核销直接完成
            $finish = true;
        }else{
            //核销类型及次数
            $verify_type = 2;
            $num = intval($num);
            if($num<=0){
                throw new UserException('请输入核销数量');
            }

            $goods = Db::name('order_goods')
                ->where('order_id','=',$order_id)
                ->field('id,num,leave_num')
                ->find();
            if(!$goods){
                throw new UserException('核销商品不存在');
            }

            if($num>$goods['leave_num']){
                throw new UserException('剩余数量不足以核销'.$num.'次');
            }

            //减剩余次数
            $save = Db::name('order_goods')
                ->where('id','=',$goods['id'])
                ->dec('leave_num',$num)
                ->update();
            if(!$save){
                throw new ServerException('核销减少次数失败');
            }

            if($num>=$goods['leave_num']){
                //按次核销已达到所有次数
                $finish = true;
            }
        }

        //核销记录
        $log = [
            'uid'=>$order['uid'],
            'merch_id'=>$order['merch_id'],
            'order_id'=>$order_id,
            'people_type'=>$type,
            'people_id'=>$admin_id,
            'name'=>$admin_name,
            'verify_type'=>$verify_type,
            'num'=>$num,
            'create_time'=>time()
        ];
        $log_id = Db::name('order_verify')->insertGetId($log);
        if(!$log_id){
            throw new ServerException('核销记录失败');
        }

        //订单完成
        if($finish){

            $change = [
                'status'=>3,
                'receive_time'=>time()
            ];

            $save = Db::name('order')
                ->where('id','=',$order_id)
                ->where('status','=',1)
                ->update($change);
            if(!$save){
                throw new ServerException('订单状态保存失败');
            }

            //订单结算
            Order::orderSettle($order);
        }

        //订单核销通知买家
        if($order['uid']){

            if($order['verify_type']==1){
                //整单核销
                $desc = "您的订单{$order['order_sn']}，已整单核销完成";
            }else{
                //按次核销
                $desc = "您的订单{$order['order_sn']}，刚刚核销了{$num}次";
            }
            Notice::systemSend(2,$order['uid'],'订单核销提醒',$desc,2,$order['id']);
        }
    }

}